package com.ifp.opengate.boot.filter;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.ifp.core.log.Trace;
import com.ifp.opengate.boot.task.*;

import reactor.core.publisher.Mono;

/**
 * @author liwq
 * @description 重新加载数据到缓存
 * @date 2021/8/31 16:24
 */
@Component
public class ReloadCacheDataGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AccessCacheDataSyncTask accessCacheDataSyncHandler;

    @Autowired
    private ApiDeployTask apiDeployTask;

    @Autowired
    private ApiGroupCacheDataTask apiGroupCacheDataTask;

    @Autowired
    private ConnectorCacheDataTask connectorCacheDataTask;

    @Autowired
    private HeaderTemplateCacheTask headerTemplateCacheTask;

    /**
     * 重新加载数据到缓存的请求URL
     */
    private static final String RELOAD_CACHE_DATA_URL = "/open-gate/reload/gateway.reloadCacheData.service";

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain chain) {
        Trace.logInfo(Trace.MODULE_FILTER, "ReloadCacheDataGlobalFilter start filter....");
        String path = serverWebExchange.getRequest().getPath().toString();
        if (RELOAD_CACHE_DATA_URL.equals(path)) {
            try {
                apiDeployTask.getApiInfoMap().clear();
                apiGroupCacheDataTask.getApiGroupInfoMap().clear();
                connectorCacheDataTask.getRouteOfMap().clear();
                connectorCacheDataTask.getRouteOfConnectorMap().clear();

                apiDeployTask.run(null);
                apiGroupCacheDataTask.run(null);
                connectorCacheDataTask.run(null);
                headerTemplateCacheTask.run(null);
                accessCacheDataSyncHandler.reload();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ServerHttpResponse httpResponse = serverWebExchange.getResponse();
            httpResponse.setStatusCode(HttpStatus.OK);
            Map<String, Object> dataMaps = new HashMap<>(4);
            dataMaps.put("result", "success");
            DataBuffer buffer = httpResponse.bufferFactory()
                .wrap(JSONObject.wrap(dataMaps).toString().getBytes(StandardCharsets.UTF_8));
            return httpResponse.writeWith(Mono.just(buffer));
        }
        return chain.filter(serverWebExchange);
    }

    @Override
    public int getOrder() {
        return -14;
    }
}
